
import os
import win32com.client
import threading
import pythoncom

from converter import Converter
from converter_error import ConverterError


class PPTConverter(Converter):
    def __init__(self, pptFileName, language, previous=None):
        Converter.__init__(self, previous)    
        self._pptFileName = os.path.abspath(pptFileName)
        self._language = language
    
    def _convertImpl(self):

        # create .jpg files

        self._imageDir = os.path.join(self.tempDir(), "images")
        print "imageDir", self._imageDir
        try:
            os.makedirs(self._imageDir)
        except OSError:
            # dir already exists, shouldn't happen
            pass
        
        notesList = []
        imageFileList = []
        
        # Because this is running in a worker thread we have to call coinitialize 
        if threading.currentThread ().getName () <> 'MainThread':
            pythoncom.CoInitialize ()
        
        try:
            Application = win32com.client.Dispatch("PowerPoint.Application") #, clsctx = pythoncom.CLSCTX_LOCAL_SERVER)
            #Application = win32com.client.gencache.EnsureDispatch("PowerPoint.Application")
        except Exception as e:
            ex = ConverterError("Powerpoint is not available", e)
            raise ex
        try:
            Application.Visible = True
            # ^ must be True, causes an exception if False
            
            Presentation = Application.Presentations.Open(self._pptFileName)
            onSlide = 0
    
            for Slide in Presentation.Slides:
                imageName = "Slide" + str(onSlide) + ".png"
                imageFileList.append(os.path.join(self._imageDir, imageName))
                Slide.Export(imageFileList[onSlide], "PNG", 800, 600) # FIXME: can this fail? need to deal with it
                onSlide += 1
                print "slide:", onSlide
                
                for Shape in Slide.NotesPage.Shapes:
                    if Shape.HasTextFrame:
                        if Shape.TextFrame.HasText:
                            text = Shape.TextFrame.TextRange.Text
                            if not text.isdigit():
                                notesList.append(text)
    
            Application.Quit()
        except Exception as ex:
            e = ConverterError("Could not convert file: %s" % (self._pptFileName))
            e.cause = ex
            raise e
        finally:
            if threading.currentThread ().getName () <> 'MainThread':
                pythoncom.CoUninitialize()
        
        # Create and populate the script data structure
        
        s = {}
        # the top level is a Sequence
        seq = []
        for i in range(len(notesList)):
            q = {}
            q['t'] = "Slide{0}".format(i)
            q['l'] = self._language
            q['q'] = notesList[i]
            # absolute path of image file
            q['i'] = imageFileList[i]
            seq.append(q)
        s['S'] = seq
        
        self._script = s
            
    def script(self):
        return self._script
